package csc.daonjpa.java.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Component;

import csc.daonjpa.java.controller.EntityManagerFactoryUtil;
import csc.daonjpa.java.domain.Account;
import csc.daonjpa.java.domain.Transaction;

@Component
public class TransactionDAO {
	public List<Transaction> getTransactions() {
		
		// Obtains entity manager object
		EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();
		
		// Obtains transaction from entity manager
		EntityTransaction entr = entityManager.getTransaction();
		
		// -----------Begin transaction-----------
		List<Transaction> transactions = null;
		try {
			entr.begin();
			// Get a list of accounts from DB
			TypedQuery<Transaction> query = entityManager.createQuery("SELECT a FROM Transaction a", Transaction.class);
			transactions = query.getResultList();
			entr.commit();
		} catch (Exception e) {
			entityManager.close();
		}
		// -----------End transaction-----------

		return transactions;
		
	}
	
	public boolean addTransaction(Transaction transaction){
		//obtains Entity Manager
		EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();
		//obtains EntityTransaction from entity manager
		EntityTransaction entr = entityManager.getTransaction();
		
		try{
			//Begin transaction
			entr.begin();
			//System.out.println("begin persist");
			entityManager.persist(transaction);
			//System.out.println("end persist");
			//Decrease amount of account
			Account account = entityManager.find(Account.class,transaction.getSoucreAccount());
			//System.out.println("Found Account to decrease amount");
			double oldAmount = account.getAvailableAmount();
			if(oldAmount>transaction.getAmount()){
				double currentAmount = oldAmount - transaction.getAmount();
				account.setAvailableAmount(currentAmount);
				System.out.println("Decreased amount of account but not commit");
			}else{
				throw new Exception();
			}
			
			entr.commit();		
			System.out.println("committed");
			//End transaction
		}catch(Exception ex){
			entr.rollback();
			entityManager.close();
		}
		
		return true;
	}
}
